package com.hqx.shiro.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hqx.shiro.base.BaseResult;
import com.hqx.shiro.model.User;
import com.hqx.shiro.model.UserRole;
import com.hqx.shiro.req.LoginReq;
import com.hqx.shiro.service.UserRoleService;
import com.hqx.shiro.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @ClassName RegisterController
 * @Description
 * @Author ph
 * @Date 2019/8/7 14:41
 * @Version 1.0
 **/
@Controller
@RequestMapping("/register")
public class RegisterController {


    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    public static final String ROOT_NUM = "1";
    public static final String ADMIN_NUM = "2";

    /**
     * 注册接口
     * @param req
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public BaseResult register(@RequestBody LoginReq req){
        User user1 = new User();
        user1.setUsername(req.getName());
        User exitUser = userService.selectOne(new EntityWrapper<>(user1));
        if(exitUser == null){
            User user = new User();
            //散列次数
            int hashIterations=2;
            user.setUsername(req.getName());
            String password = req.getPwd();
            Md5Hash md5Hash=new Md5Hash(password, null, hashIterations);
            user.setPassword(md5Hash.toString());
            boolean b = userService.insert(user);

            if(b){
                //给角色
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getId());
                userRole.setRoleId(ADMIN_NUM);
                userRole.setRemarks("ph是管理员具有goods修改的权限");
                userRoleService.insert(userRole);
                return BaseResult.success("注册成功");
            }else {
                return BaseResult.error("注册失败，请联系管理员");
            }

        }else{
            return BaseResult.error("用户已经存在了");
        }
    }

}
